package org.webbase.demo.web;

import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.webbase.common.Paginator;
import org.webbase.demo.pojo.Demo;
import org.webbase.demo.service.DemoService;
import org.webbase.system.web.ModelAction;

@Controller
@RequestMapping(value="/demo")
public class DemoAction extends ModelAction<Demo> {

	@Autowired private DemoService demoService;

	@RequestMapping(method=RequestMethod.GET)
	public String list() {
		Paginator<Demo> pagin=getPaginator();
		demoService.find(pagin);
		return "demo/demo-list";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add() {
		return "demo/demo-update";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	public boolean doAdd(Demo demo) {
		demo.setCreateTime(new Date());
		demoService.add(demo);
		return true;
	}
	
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String update(@PathVariable String id) {
		Demo demo=demoService.get(id);
		attr("demo", demo);
		return "demo/demo-update";
	}
	
	@RequestMapping(value="/update/{id}",method=RequestMethod.POST)
	@ResponseBody
	public boolean doUpdate(@PathVariable String id,Demo demo) {
		demoService.update(demo);
		return true;
	}
	
	@RequestMapping(value="/delete/{id}",method=RequestMethod.GET)
	public String doDelete(@PathVariable String id) {
		demoService.delete(id);
		return redirect("/demo");
	}
	
	/**
	 * 返回json 方式1:由sprong mvc提供
	 * @param request
	 * @return
	 */
	@RequestMapping("/json1")
	@ResponseBody
	public Demo json1() {
		Demo demo=new Demo();
		demo.setBirthday(new Date());
		demo.setCreateTime(new Date());
		demo.setHeight(170);
		demo.setName("tomcat");
		demo.setRemark("json测试");
		demo.setStatus((short)1);
		return demo;
	}
	
	/**
	 * 返回json 方式2:由用户自定义
	 */
	@RequestMapping("/json2")
	public void json2(HttpServletResponse response) {
		Demo demo=new Demo();
		demo.setBirthday(new Date());
		demo.setCreateTime(new Date());
		demo.setHeight(170);
		demo.setName("tomcat");
		demo.setRemark("json测试");
		demo.setStatus((short)1);
		printjson(response,demo);
	}
}
